package com.shopping_center.management.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author YeFeng
 * @date 2023/2/2
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Throwable.class)
    public DataWrapper<?> handleThrowable(Throwable e, HttpServletRequest request) {
        log.error("URL:{} ,系统异常: ", request.getRequestURI());
        return DataWrapper.errorOf(ResultCode.SYSTEM_EXCEPTION);
    }

    @ExceptionHandler(BindException.class)
    public DataWrapper<?> exceptionHandler(BindException e, HttpServletRequest request) {
        String failMsg = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        log.error("URL:{} ,绑定异常:{} ", request.getRequestURI(), failMsg);
        return DataWrapper.errorWithData(ResultCode.SYSTEM_EXCEPTION, failMsg);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public DataWrapper<?> exceptionHandler(MethodArgumentNotValidException e) {
        String defaultMessage = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return DataWrapper.errorWithData(ResultCode.SYSTEM_EXCEPTION, defaultMessage);
    }
}
